package com.changzhou.chatroom.service.impl;

import com.changzhou.chatroom.Request.LoginRequest;
import com.changzhou.chatroom.mapper.RegistMapper;
import com.changzhou.chatroom.mapper.UserMapper;
import com.changzhou.chatroom.pojo.Result;
import com.changzhou.chatroom.pojo.User;
import com.changzhou.chatroom.service.UserService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 用户服务实现类
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RegistMapper registMapper;
    /**
     * 用户注册
     * @param user 用户信息
     * @return 注册是否成功
     */
    @Override
    public boolean register(User user) {
        User user1 = new User();
        user1.setUsername(user.getUsername());
        //如果当前有相同的用户
        User username = userMapper.selectOne(user1);
        if(username != null)
        {
            return false;
        }
        else {
            String id = UUID.randomUUID().toString().replace("-", "");
            user.setUserId(id);
            registMapper.insert(user);
            return true;
        }

    }

    @Override
    public Result login(LoginRequest request, HttpSession session, HttpServletResponse response) {
        Result result = new Result();
        User user = new User();
        String password = request.getPassword();
        String username = request.getUsername();
        user.setUsername(username);
        user.setPassword(password);
        User loginUser = userMapper.selectOne(user);
        if(loginUser != null)
        {
            result.setFlag(true);
            result.setMessage("登录成功");
            clearRememberCookies(response);
            // 1. 将用户名存入Session
            session.setAttribute("user", loginUser.getUsername());
            String token = user.getUsername();
            //在seesion中放置一个token 左检验
             session.setAttribute("token",token);
            // 2. 检查是否勾选"记住我"
            if (request.isRememberMe()) {
                // 创建记住用户名的Cookie（30天有效期）
                clearRememberCookies(response);
                Cookie usernameCookie = new Cookie("rememberedUser", loginUser.getUsername());
                usernameCookie.setMaxAge(30 * 24 * 60 * 60); // 30天
                usernameCookie.setPath("/");
                usernameCookie.setHttpOnly(false); // 防止XSS攻击
                response.addCookie(usernameCookie);

                // 创建记住密码的Cookie（实际应用中应加密）
                // 注意：生产环境中密码应该加密存储
                Cookie passwordCookie = new Cookie("rememberedPass", request.getPassword());
                passwordCookie.setMaxAge(30 * 24 * 60 * 60);
                passwordCookie.setPath("/");
                passwordCookie.setHttpOnly(false);
                response.addCookie(passwordCookie);
                }
            } else {
            result.setFlag(false);
            result.setMessage("用户登录失败");
            // 清除可能存在的记住密码Cookie
            clearRememberCookies(response);
        }
        return result;
    }
    // 清除记住密码的Cookie
    private void clearRememberCookies(HttpServletResponse response) {
        Cookie usernameCookie = new Cookie("rememberedUser", "");
        usernameCookie.setMaxAge(0);
        usernameCookie.setPath("/");
        response.addCookie(usernameCookie);

        Cookie passwordCookie = new Cookie("rememberedPass", "");
        passwordCookie.setMaxAge(0);
        passwordCookie.setPath("/");
        response.addCookie(passwordCookie);
    }
}